<?php

namespace app\common\model;

use app\api\model\WxMessage;
use app\common\model\AppointmentService as ServiceModel;
use app\common\service\Order as OrderService;
use app\common\model\UploadFile as UploadFileModel;
use app\api\model\OrderGoods as GoodsModel;
use app\api\model\sharing\OrderGoods as SharingGoodsModel;
use app\api\model\Order as OrderModel;
use think\App;
use think\Db;

/**
 * 预约模型
 * sxc 2020-8-18
 * Class Article
 * @package app\common\model
 */
class AppointmentOrder extends BaseModel
{
    protected $name = 'appointment_order';

    /**
     * 商品规格是否已使用
     * @param $user_id
     * @param $order_id
     * @param $goods_id
     * @param $sku_id
     * @return bool
     */
    public function isUse($user_id, $order_id, $goods_id, $sku_id)
    {
        $order = OrderModel::detail(['order_id' => $order_id]);
        if ($order) {
            $sku = Db("order_goods")
                ->where('order_id', $order_id)
                ->where('goods_id', $goods_id)
                ->where('user_id', $user_id)
                ->field('goods_sku_id,goods_sku_ids,total_num,create_time')
                ->find();
        } else {
            $sku = Db("sharing_order_goods")
                ->where('order_id', $order_id)
                ->where('goods_id', $goods_id)
                ->where('user_id', $user_id)
                ->field('goods_sku_id,total_num,create_time')
                ->find();
        }

        //判断订单规格是否存在
        if (empty($sku)) {
            $this->error = '订单商品未找到';
            return false;
        }

        //普通订单和套餐判断规格是否存在
//        if ($sku['goods_sku_id'] != $sku_id || !in_array($sku_id, explode(',', $sku['goods_sku_id']))) {
//            $this->error = '订单商品规格未找到';
//            return false;
//        }

        $where = [
            'user_goods_id' => $goods_id,
            'user_goods_sku' => $sku_id,
            'user_order_id' => $order_id,
            'user_id' => $user_id,
            'is_delete' => 0,
            'wxapp_id' => self::$wxapp_id,
        ];

        //判断购买商品规格的数量是否用完
        $count = $this->where($where)
            ->where('status', 'in', [1, 2])->count();
//        var_dump($order);
        if ($order) {
            $goods = GoodsModel::detail([
                'order_id' => $order_id,
                'goods_id' => $goods_id,
            ]);
        } else {
            $goods = SharingGoodsModel::detail([
                'order_id' => $order_id,
                'goods_id' => $goods_id,
            ]);
        }

        switch ($goods['goods_type']) {
            case 0:
                if ($count >= $sku['total_num']) {
                    $this->error = '商品预约已用完';
                    return false;
                }
                break;
            case 1:  //按次
                if ($goods['goods_expire'] > 60) {
                    $this->error = '有效期配置有误';
                    return false;
                }

                $expire_time = $goods['goods_expire'] * 3600 * 24 * 30;
//                log_print($expire_time, $goods['goods_expire'], $sku['create_time']);
                if (time() - $expire_time > $sku['create_time']) {
                    $this->error = '服务卡已过期';
                    return false;
                }

                if ($count >= $goods['goods_count']) {
                    $this->error = '商品预约已用完';
                    return false;
                }
                break;
            case 2:  //包月
                $month1 = strtotime(date("Y-m-01", time()));
                $month2 = strtotime(date("Y-m-01", strtotime('+1 months')));

                $where1 = "appointment_date >=" . $month1 . " and appointment_date <=" . $month2;
                $count = $this->where($where)
                    ->where($where1)
                    ->where('status', 'in', [1, 2])->count();
                log_print($this->getLastSql(), $goods['goods_count_month']);
                if ($count >= $goods['goods_count_month']) {
                    $this->error = '当月服务次数已使用完毕，请下月再进行预约';
                    return false;
                }

                $month = date("m", $sku['create_time']);
                $cur_month = date("m", time());
                if ($cur_month < $month) $cur_month = $cur_month + 12;
//                log_print($cur_month, $month, $goods['goods_month']);
                if ($cur_month - $month > $goods['goods_month']) {
                    $this->error = '服务卡已过期';
                    return false;
                }
                break;
            case 3: //套餐
                if ($count >= $sku['total_num']) {
                    $this->error = '商品预约已用完';
                    return false;
                }
                break;
            case 4: //預約卡
                $goods_info = Goods::get($goods['goods_id']);

                if($goods_info['goods_start_time'] > time()){
                    $this->error = '还未到可以使用时间';
                    return false;
                }
                if($goods_info['goods_over_time'] < time()){
                    $this->error = '卡已过期';
                    return false;
                }
                break;
        }

        //判断是否有预约的商品规格
        $order = $this
            ->where('user_order_id', $order_id)
            ->where('user_goods_sku', $sku_id)
            ->where('user_id', $user_id)
            ->where('status', 1)
            ->where('is_delete', 0)->find();
        if ($order) {
            $this->error = '已预约，等待师傅上门';
            return false;
        }

        return true;
    }

    public function confirmOrderFinish($order_id)
    {
        $order_goods = Db("order_goods")
            ->where('order_id', $order_id)
            ->field('goods_type,goods_count,goods_count_month,goods_month,
            goods_expire,total_num,goods_id,goods_sku_id,create_time,goods_meal_num')
            ->select();
        //判断订单规格是否存在
        if (empty($order_goods)) {
            $this->error = '订单商品未找到';
            return false;
        }

        $where = [
            'user_order_id' => $order_id,
            'is_delete' => 0,
            'wxapp_id' => self::$wxapp_id,
        ];

        $is_finish = false;
        $arr_finish = [];
        foreach ($order_goods as $k => $v) {
            switch ($v['goods_type']) {
                case 0:
//                    $where['user_goods_id'] = $v['goods_id'];
//                    $where['user_goods_sku'] = $v['goods_sku_id'];
//                    $count = $this->where($where)
//                        ->where('status', 2)->count();
//                    if ($count < $v['total_num']) {
//                        $arr_finish[$k] = 0;
//                    } else {
//                        $arr_finish[$k] = 1;
//                    }
                    $arr_finish[$k] = 1;
                    break;
                case 1:
                    //判断购买商品规格的数量是否用完
                    $count = $this->where($where)
                        ->where('status', 2)->count();

                    $expire_time = $v['goods_expire'] * 3600 * 24 * 12;
                    if (time() - $expire_time > $v['create_time']) {
                        $is_finish = true;
                        log_print(time(), $expire_time, $v['create_time']);
                    }

                    if ($count == $v['goods_count']) {
                        $is_finish = true;
                        log_print($count, $v['goods_count']);
                    }
                    break;
                case 2:
                    $count = $this->where($where)
                        ->where('status', 2)
                        ->count();

                    if ($count >= $v['goods_count_month'] * $v['goods_month']) {
                        $is_finish = true;
                    }

                    $month = date("m", $v['create_time']);
                    $cur_month = date("m", time());
                    if ($cur_month < $month) $cur_month = $cur_month + 12;

                    if ($cur_month - $month > $v['goods_month']) {
                        $is_finish = true;
                    }
                    break;
                case 3:
                    $count = $this->where($where)
                        ->where('status', 2)
                        ->count();
                    if ($count == $v['goods_meal_num']) $is_finish = true;
                    break;
                case 4:
//                    $where['user_goods_id'] = $v['goods_id'];
//                    $where['user_goods_sku'] = $v['goods_sku_id'];
//                    $count = $this->where($where)
//                        ->where('status', 2)->count();
//                    if ($count < $v['total_num']) {
//                        $arr_finish[$k] = 0;
//                    } else {
//                        $arr_finish[$k] = 1;
//                    }
                    $arr_finish[$k] = 1;
                    break;
            }
        }

        if (count($arr_finish) > 0) {
            $count = 0;
            foreach ($arr_finish as $v) {
                if ($v == 1) $count++;
            }
            if ($count == count($arr_finish)) $is_finish = true;
        }

        if ($is_finish) {
            Db("order")->where('order_id', $order_id)->update([
                'order_status' => 30,
            ]);
            return true;
        }else{
            Db("order")->where('order_id', $order_id)->update([
                'order_status' => 10,
            ]);
        }

        return false;
    }

    /**
     * 获取当前日期下的预约状态
     * @param $date
     * @param $type_id
     * @return mixed
     */
    public function getStateByDate($date, $type_id)
    {
        $date = strtotime($date);

        //获取当前类型的服务人员个数
        $where = [
            'wxapp_id' => self::$wxapp_id,
            'is_delete' => 0,
            'type_id' => $type_id,
        ];
        $count = Db("appointment_type")
            ->where($where)
            ->value('count');

        $list = Db('appointment_time')
            ->where($where)
            ->where('status', 1)
            ->field('time_id,name,desc')
            ->order("sort asc")
            ->select()->toArray();

        $cur_date = strtotime(date("Y-m-d", time()));
        $lower_state = $cur_date - $date == 0 ? 1 : 0;
        foreach ($list as $k => $v) {
            $use_count = Db("appointment_order")
                ->where("appointment_date", $date)
//                ->where("time_id", $v['time_id'])
                ->where('find_in_set(:time_id,time_id)',['time_id'=>$v['time_id']])
                ->where("status", 'in', [1, 2])
                ->where($where)
                ->count();
            $state = false;
            $arr = explode('~', $v['desc']);
            if ($lower_state && count($arr) == 2) {
                $m1 = getMinute(date("H:m", time()));
                $m2 = getMinute($arr[1]);
                if ($m1 >= $m2) {
                    $list[$k]['use_count'] = 0;
                    $state = true;
                }
            }

            if (!$state) {
                $config_count = Db("appointment_config")
                    ->where("type_id", $type_id)
                    ->where("date", $date)
                    ->where('find_in_set(:time_id,time_id)',['time_id'=>$v['time_id']])
                    ->where($where)->find();
                $sql = Db("appointment_config")->getLastSql();
                $all_count = isset($config_count['count']) ? $config_count['count'] : $count;
                $list[$k]['use_count'] = ($all_count - $use_count) <= 0 ? 0 : ($all_count - $use_count);
            }
        }

        return $list;
    }

    /**
     * 获取当前日期下的预约状态-服务人员
     * @param $date
     * @param $type_id
     * @return mixed
     */
    public function getStateByDateService($date, $type_id, $user_id, $cur_date, $time_id)
    {
        $date = strtotime($date);

        //获取当前类型的服务人员个数
        $where = [
            'wxapp_id' => self::$wxapp_id,
            'is_delete' => 0,
            'type_id' => $type_id,
        ];
        $list = Db('appointment_time')
            ->where($where)
            ->where('status', 1)
            ->field('time_id,name,desc')
            ->order("sort asc")
            ->select()->toArray();

        $day_date = strtotime(date("Y-m-d", time()));
        $lower_state = $day_date - $date >= 0 ? 1 : 0;
        foreach ($list as $k => $v) {
            $use_count = Db("appointment_order")
                ->where("appointment_date", $date)
                ->where("time_id", $v['time_id'])
                ->where("status", 'in', [1, 2])
                ->where("service_id", $user_id)
                ->where($where)
                ->find();

            $state = false;
            $arr = explode('~', $v['desc']);
            if ($lower_state && count($arr) == 2) {
                $m1 = getMinute(date("H:m", time()));
                $m2 = getMinute($arr[1]);
                if ($m1 >= $m2) {
                    $list[$k]['use_count'] = 0;
                    $state = true;
                }
            }

            if (!$state) {
                $list[$k]['use_count'] = $use_count ? 0 : 1;
            }

            $state = ($date == $cur_date && $v['time_id'] == $time_id) ? 1 : 0;
            $list[$k]['is_user'] = $state;
            if ($state) $list[$k]['use_count'] = 1;
        }

        return $list;
    }

    /**
     * 判断是否可以预约
     * @param $type_id
     * @param $date
     * @param $time_id
     * @return bool
     */
    public function isOk($type_id, $date, $time_id, $order_id, $goods_id)
    {
        $date = strtotime($date);

        $where = [
            'wxapp_id' => self::$wxapp_id,
            'is_delete' => 0,
        ];

        $count = Db("appointment_type")
            ->where($where)
            ->where('type_id', $type_id)->value('count');

        $time_arr = explode(',',$time_id);

        foreach ($time_arr as $val){
            $use_count = AppointmentOrder::where("appointment_date", $date)
                ->where('find_in_set(:time_id,time_id)',['time_id'=>$val])
                ->where("status", 'in', [1, 2])
                ->where($where)
                ->count();

            $config_count = Db("appointment_config")
                ->where("type_id", $type_id)
                ->where("date", $date)
                ->where("time_id", $val)
                ->where($where)->find();
            $all_count = isset($config_count['count']) ? $config_count['count'] : $count;

            $team_name = Db::name('appointment_time')->where(['time_id'=>$val])->value('name');
            $date_name = date('Y-m-d',$date);
            if ($all_count - $use_count == 0) {
                $this->error = $date_name.$team_name.'没有可预约的工作人员';
                return false;
            }

        }

//
//        $use_count = Db("appointment_order")
//            ->where("appointment_date", $date)
//            ->where("time_id", $time_id)
//            ->where("status", 'in', [1, 2])
//            ->where($where)
//            ->count();
//
//        $config_count = Db("appointment_config")
//            ->where("type_id", $type_id)
//            ->where("date", $date)
//            ->where("time_id", $time_id)
//            ->where($where)->find();
//        $all_count = isset($config_count['count']) ? $config_count['count'] : $count;
//
//        if ($all_count - $use_count == 0) {
//            $this->error = '没有可预约的工作人员';
//            return false;
//        }

        //如果是包月卡，判断是否是当月预约
        $OrderGoods = new orderGoods();
        $goods = $OrderGoods->where([
            'order_id' => $order_id,
            'goods_id' => $goods_id,
        ])->find();
        if (!empty($goods) && $goods['goods_type'] == 2) {
            $month1 = strtotime(date("Y-m-01", time()));
            $month2 = strtotime(date("Y-m-01", strtotime('+1 months')));
            if ($month1 > $date || $month2 < $date) {
                $this->error = '包月套餐只能预约当月的';
                return false;
            }
        }

        if (!empty($goods) && $goods['goods_type'] == 4) {
            if ($date < $goods['goods_start_time']) {
                $this->error = '还未到可以预约的时间';
                return false;
            }
            if ($date > $goods['goods_over_time']) {
                $this->error = '已超过可以预约的时间';
                return false;
            }
        }
        return true;
    }

    /**
     * 添加预约
     * @param $data
     * @return bool|mixed
     */
    public function add($data = [])
    {
        $where = [
            'wxapp_id' => self::$wxapp_id,
            'is_delete' => 0,
        ];

        if (!isset($data['user_id'])) {
            $this->error = '请选择用户信息';
            return false;
        }

        if (empty($data['type_id'])) {
            $this->error = '预约类型未选择';
            return false;
        }

        if (empty($data['appointment_date'])) {
            $this->error = '预约日期未选择';
            return false;
        }

        if (empty($data['user_id'])) {
            $this->error = '用户信息不能为空';
            return false;
        }

        if (empty($data['user_name'])) {
            $this->error = '名称不能为空';
            return false;
        }

        if (empty($data['user_phone'])) {
            $this->error = '手机号不能为空';
            return false;
        }

        if (empty($data['address'])) {
            $this->error = '地址不能为空';
            return false;
        }

        $data['order_id'] = OrderService::createOrderNo();
        $data['appointment_date'] = strtotime($data['appointment_date']);

        if (empty($data['time_id'])) {
            $this->error = '时间点未选择';
            return false;
        }

        if (empty($data['user_order_id'])) {
            $this->error = '客户的订单未选择';
            return false;
        }

        if (empty($data['user_goods_id'])) {
            $this->error = '订单商品未选择';
            return false;
        }

        if (empty($data['user_goods_sku'])) {
            $this->error = '订单商品规格未选择';
            return false;
        }

        $exist = $this->where($where)
            ->where('user_id', $data['user_id'])
            ->where('type_id', $data['type_id'])
            ->where('appointment_date', $data['appointment_date'])
            ->where('time_id', $data['time_id'])
            ->where('user_order_id', $data['user_order_id'])
            ->where('user_goods_id', $data['user_goods_id'])
            ->where('user_goods_sku', $data['user_goods_sku'])
            ->find();
        if ($exist) {
            $this->error = '同一时间段，只能预约服务一次';
            return false;
        }


        $data['wxapp_id'] = self::$wxapp_id;
        return $this->allowField(true)->save($data);
    }

    /*
     * 获取会员卡信息
     */
    public function cardInfo($user_id, $order_id, $goods_id, $sku_id)
    {
        $where = [
            'o.wxapp_id' => self::$wxapp_id,
            'o.is_delete' => 0,
        ];
        //次卡列表
        $detail = Db("order")->alias('o')
            ->join("order_goods o_g", 'o_g.order_id = o.order_id', 'left')
            ->join("goods_image g_i", 'g_i.goods_id = o_g.goods_id', 'left')
            ->where('o.order_id', $order_id)
            ->where('o.user_id', $user_id)
            ->where('o_g.goods_type', 1)
            ->where($where)
            ->field("o.order_id,o_g.goods_id,o_g.goods_name,o_g.selling_point,g_i.image_id,
            o_g.goods_count,o_g.type_id,o_g.goods_price")
            ->find();
        if (!$detail) {
            $this->error = '预约信息未找到';
            return false;
        }

        $uploadFile = new UploadFileModel;
        $image = $uploadFile->detail($detail['image_id']);
        $detail['image'] = $image['file_path'];

        $count = $this->where('user_order_id', $order_id)
            ->where('status', 'in', [1, 2])
            ->count();

        $detail['remain'] = $detail['goods_count'] - $count;

        return $detail;

    }

    /**
     * 获取服务列表
     * @param $user_id
     * @return array
     */
    public function lists($user_id)
    {
        $where = [
            'o.wxapp_id' => self::$wxapp_id,
            'o.is_delete' => 0,
        ];

        //次卡列表
        $list_1 = Db("order")->alias('o')
            ->join("order_goods o_g", 'o_g.order_id = o.order_id', 'left')
            ->join("goods_image g_i", 'g_i.goods_id = o_g.goods_id', 'left')
            ->where('o.user_id', $user_id)
            ->where('o.pay_status', 20)
            ->whereIn('o.order_status', "10,40")
            ->where('o_g.goods_type', 1)
            ->where($where)
            ->group("o.order_id")
            ->field("o.order_id order_id,o_g.goods_name,o_g.selling_point,
            o_g.goods_count,o.total_price,g_i.image_id,o.create_time")
            ->order("o.create_time desc")
            ->select();
        $list_1 = collection($list_1)->toArray();

        $uploadFile = new UploadFileModel;
        foreach ($list_1 as $k => &$v) {
            $count = $this->where('user_order_id', $v['order_id'])
                ->where('status', 'in', [1, 2])
                ->count();

            $run = $this->where('user_order_id', $v['order_id'])
                ->where('status', 1)
                ->count();

            $image = $uploadFile->detail($v['image_id']);
            $list_1[$k]['image'] = $image['file_path'];

            $list_1[$k]['is_run'] = $run == 1 ? 1 : 0;
            $list_1[$k]['remain'] = $v['goods_count'] - $count;
        }

        $month_1 = strtotime(date("Y-m-1", time()));
        $month_2 = date("Y-m-1", strtotime('+1 month'));

        //包月列表
        $list_2 = Db("order")->alias('o')
            ->join("order_goods o_g", 'o_g.order_id = o.order_id', 'left')
            ->join("goods_image i", 'i.goods_id = o_g.goods_id', 'left')
            ->where('o.user_id', $user_id)
            ->where('o.pay_status', 20)
            ->whereIn('o.order_status', "10,40")
            ->where('o_g.goods_type', 2)
            ->where($where)
            ->group("o.order_id")
            ->field("o.order_id order_id,o_g.goods_name,o_g.selling_point,o_g.goods_count_month,
            i.image_id,o_g.total_price,o.create_time")
            ->order("o.create_time desc")
            ->select();
        $list_2 = collection($list_2)->toArray();
        $uploadFile = new UploadFileModel;
        foreach ($list_2 as $k => &$v) {
            $count = $this->where('user_order_id', $v['order_id'])
                ->where('appointment_date', 'between', [$month_1, $month_2])
                ->where('status', 2)
                ->count();
            if ($count == $v['goods_count_month']) {
                $v['is_end'] = 1;
            } else {
                $v['is_end'] = 0;
            }

            $run = $this->where('user_order_id', $v['order_id'])
                ->where('appointment_date', 'between', [$month_1, $month_2])
                ->where('status', 1)
                ->count();
            $v['is_run'] = $run == 1 ? 1 : 0;
            $image = $uploadFile->detail($v['image_id']);
            $v['image'] = $image['file_path'];
        }

        //服务商品列表
        $list_3 = Db("order")->alias('o')
            ->join("order_goods o_g", 'o_g.order_id = o.order_id', 'left')
            ->join("goods_image i", 'i.goods_id = o_g.goods_id', 'left')
            ->where('o.user_id', $user_id)
            ->where('o.pay_status', 20)
            ->whereIn('o.order_status', "10,40")
            ->where('o_g.goods_type', 0)
            ->where($where)
            ->group("o.order_id")
            ->field("o.order_id,o_g.goods_name,o_g.selling_point,i.image_id,
            o.total_price,o.create_time")
            ->order("o.create_time desc")
            ->select();
        $list_3 = collection($list_3)->toArray();
        foreach ($list_3 as $k => &$v) {
            $v['is_run'] = 0;

            $image = $uploadFile->detail($v['image_id']);
            $v['image'] = $image['file_path'];
        }

        //套餐列表
        $list_4 = Db("order")->alias('o')
            ->join("order_goods o_g", 'o_g.order_id = o.order_id', 'left')
            ->join("goods_image i", 'i.goods_id = o_g.goods_id', 'left')
            ->where('o.user_id', $user_id)
            ->where('o.pay_status', 20)
            ->whereIn('o.order_status', "10,40")
            ->where('o_g.goods_type', 3)
            ->where($where)
            ->group("o.order_id")
            ->field("o.order_id,o_g.goods_name,o_g.selling_point,i.image_id,o.total_price,o.create_time")
            ->order("o.create_time desc")
            ->select();
        $list_4 = collection($list_4)->toArray();
        foreach ($list_4 as $k => &$v) {
            $v['is_run'] = 0;

            $image = $uploadFile->detail($v['image_id']);
            $v['image'] = $image['file_path'];
        }

        //拼团预约
        $list_5 = Db("sharing_order")->alias('o')
            ->join("sharing_order_goods o_g", 'o_g.order_id = o.order_id', 'left')
            ->join("sharing_goods_image i", 'i.goods_id = o_g.goods_id', 'left')
            ->join("sharing_active a", 'o.active_id = a.active_id', 'left')
            ->where('o.user_id', $user_id)
            ->where('o.pay_status', 20)
            ->whereIn('o.order_status', "10,40")
            ->where('o_g.goods_type', 0)
            ->where("a.active_id is null or a.active_id = 20")
            ->where($where)
            ->group("o.order_id")
            ->field("o.order_id,o_g.goods_name,o_g.selling_point,i.image_id,
            o.total_price,o.create_time,a.status")
            ->order("o.create_time desc")
            ->select();
        log_print(Db("sharing_order")->getLastSql());
        $list_5 = collection($list_5)->toArray();
        foreach ($list_5 as $k => &$v) {
            $v['is_run'] = 0;
            $image = $uploadFile->detail($v['image_id']);
            $v['image'] = $image['file_path'];
        }

        //拼团预约
        $list_6 = Db("order")->alias('o')
            ->join("order_goods o_g", 'o_g.order_id = o.order_id', 'left')
            ->join("goods_image i", 'i.goods_id = o_g.goods_id', 'left')
            ->where('o.user_id', $user_id)
            ->where('o.pay_status', 20)
            ->whereIn('o.order_status', "10,40")
            ->where('o_g.goods_type', 4)
            ->where($where)
            ->group("o.order_id")
            ->field("o.order_id,o_g.goods_name,o_g.selling_point,i.image_id,o.total_price,o.create_time")
            ->order("o.create_time desc")
            ->select();
        $list_6 = collection($list_6)->toArray();
        foreach ($list_6 as $k => &$v) {
            $v['is_run'] = 0;

            $image = $uploadFile->detail($v['image_id']);
            $v['image'] = $image['file_path'];
        }

        return [
            'list_1' => $list_1,
            'list_2' => $list_2,
            'list_3' => $list_3,
            'list_4' => $list_4,
            'list_5' => $list_5,
            'list_6' => $list_6
        ];
    }

    /**
     * 按次详情
     * @param $oder_id
     * @return array|bool|false|\PDOStatement|string|\think\Model
     */
    function timeDetail($order_id)
    {
        $where = [
            'o.wxapp_id' => self::$wxapp_id,
            'o.is_delete' => 0,
        ];

        //次卡列表
        $detail = Db("order")->alias('o')
            ->join("order_goods o_g", 'o_g.order_id = o.order_id', 'left')
            ->join("goods_image g_i", 'g_i.goods_id = o_g.goods_id', 'left')
            ->where('o.order_id', $order_id)
            ->where('o.pay_status', 20)
            ->whereIn('o.order_status', "10,40")
            ->where('o_g.goods_type', 1)
            ->where($where)
            ->field("o.order_id,o_g.goods_id,o_g.goods_sku_id,o_g.goods_name,o_g.selling_point,
            o_g.goods_count,g_i.image_id,o_g.type_id,o_g.goods_price")
            ->find();

        if (empty($detail)) {
            $this->error = "订单不存在";
            return false;
        }
        $uploadFile = new UploadFileModel;
        $image = $uploadFile->detail($detail['image_id']);
        $detail['image'] = $image['file_path'];

        $count = $this->where('user_order_id', $order_id)
            ->where('status', 'in', [1, 2])
            ->count();

        $detail['remain'] = $detail['goods_count'] - $count;

        $appointment = $this->alias('a')
            ->join('server_user u', 'u.user_id = a.service_id', 'left')
            ->join('appointment_time t', 't.time_id = a.time_id', 'left')
            ->join('appointment_service s', 's.order_id = a.id', 'left')
            ->where('a.user_order_id', $order_id)
            ->where('a.status', 'in', [1, 2])
            ->field('a.id order_id,u.real_name serviceName,a.appointment_date,a.service_status,
            a.user_name,a.user_phone,a.address,t.name time_name,t.desc,a.status status,s.use_time,s.start_time,s.end_time,a.time_id')
            ->order("a.status desc,a.create_time desc")
            ->select();

        $appointment = collection($appointment)->toArray();
        foreach ($appointment as $k => $v) {
            $this->appointment_value($appointment[$k]);

        }
        $detail['is_yuyue'] = 1;
        $detail['appointment'] = $appointment;

        return $detail;
    }

    /**
     * 包月卡
     * @param $order_id
     * @return array|bool|false|\PDOStatement|string|\think\Model
     */
    function monthDetail($order_id)
    {
        $where = [
            'o.wxapp_id' => self::$wxapp_id,
            'o.is_delete' => 0,
        ];

        //包月列表
        $detail = Db("order")->alias('o')
            ->join("order_goods o_g", 'o_g.order_id = o.order_id', 'left')
            ->join("goods_image g_i", 'g_i.goods_id = o_g.goods_id', 'left')
            ->where('o.order_id', $order_id)
            ->where('o.pay_status', 20)
            ->whereIn('o.order_status', "10,40")
            ->where('o_g.goods_type', 2)
            ->where($where)
            ->field("o.order_id,o_g.goods_id,o_g.goods_sku_id,o_g.goods_name,o_g.type_id,
            o_g.selling_point,o_g.goods_month goods_month,o_g.goods_count_month,g_i.image_id,o_g.goods_price")
            ->find();
        if (empty($detail)) {
            $this->error = "订单不存在";
            return false;
        }
        $uploadFile = new UploadFileModel;
        $image = $uploadFile->detail($detail['image_id']);
        $detail['image'] = $image['file_path'];

        $month1 = strtotime(date("Y-m-01", time()));
        $month2 = strtotime(date("Y-m-01", strtotime('+1 months')));
        $where1 = 'create_time >=' . $month1 . ' and create_time <=' . $month2;
        $count = $this->where('user_order_id', $order_id)
            ->where($where1)
            ->where('status', 'in', [1, 2])
            ->count();

        $create_time = $this->alias('a')
            ->where('a.user_order_id', $order_id)
            ->where('a.status', 'in', [1, 2])
            ->value('a.create_time');
        if ($create_time > 0) {
            $start_month = date("m", $create_time);
        } else {
            $start_month = date("m", time());
        }

        $cur_month = date("m", time());
        if ($cur_month < $start_month) $cur_month = $cur_month + 12;

        $detail['remain_month'] = $detail['goods_month'] - ($cur_month - $start_month) > 0 ?
            $detail['goods_month'] - ($cur_month - $start_month) - 1 : 0;
        $detail['cur_month'] = $detail['goods_count_month'] - $count;
        log_print($detail['goods_month'], $detail['goods_count_month'], $count, $start_month, $cur_month);

        $appointment = $this->alias('a')
            ->join('server_user u', 'u.user_id = a.service_id', 'left')
            ->join('appointment_time t', 't.time_id = a.time_id', 'left')
            ->join('appointment_service s', 's.order_id = a.id', 'left')
            ->where('a.user_order_id', $order_id)
            ->where('a.status', 'in', [1, 2])
            ->field('u.real_name serviceName,a.appointment_date,a.user_name,a.user_phone,a.address,a.service_status,
            t.name time_name,t.desc,a.status,s.use_time,s.start_time,s.end_time,a.id order_id,a.time_id')
            ->order("a.status desc,a.create_time desc")
            ->select();

        $appointment = collection($appointment)->toArray();
        foreach ($appointment as $k => $v) {
            $this->appointment_value($appointment[$k]);
        }
        $detail['is_yuyue'] = 1;
        $detail['appointment'] = $appointment;

        return $detail;
    }

    /**
     * 套餐详情
     * @param $order
     * @return array|bool|false|\PDOStatement|string|\think\Model
     */
    function packetDetail($order_id)
    {
        $where = [
            'o_g.wxapp_id' => self::$wxapp_id,
        ];

        //套餐列表
        $detail = Db("order_goods")->alias('o_g')
            ->join("order o", 'o_g.order_id = o.order_id', 'left')
            ->join("goods_image g_i", 'g_i.goods_id = o_g.goods_id', 'left')
            ->where('o.order_id', $order_id)
            ->where('o.pay_status', 20)
            ->whereIn('o.order_status', "10,40")
            ->where('o_g.goods_type', 3)
            ->where($where)
            ->field("o_g.goods_sku_ids,o_g.goods_id,o_g.order_id order_id,o_g.goods_name,
            o_g.selling_point,g_i.image_id")
            ->find();
        if (empty($detail)) {
            $this->error = "订单不存在";
            return false;
        }

        $uploadFile = new UploadFileModel;
        $image = $uploadFile->detail($detail['image_id']);
        $detail['image'] = $image['file_path'];

        $skus = Db("goods_sku_copy")->where([
            'goods_id' => $detail['goods_id'],
            'goods_sku_id' => ['in', explode(',', $detail['goods_sku_ids'])],
        ])->field('goods_id,goods_sku_id,image_id,goods_no,goods_sku_name,type_id')->select();
        $skus = collection($skus)->toArray();
        foreach ($skus as $k => $v) {
            $image = $uploadFile->detail($detail['image_id']);
            $skus[$k]['image'] = $image['file_path'];

            $appointment = $this->alias('a')
                ->join('appointment_service s', 's.order_id = a.id', 'left')
                ->join('server_user u', 'u.user_id = s.service_id', 'left')
                ->join('appointment_time t', 't.time_id = a.time_id', 'left')
                ->where([
                    'user_order_id' => $detail['order_id'],
                    'user_goods_id' => $detail['goods_id'],
                    'user_goods_sku' => $v['goods_sku_id'],
                ])->field('a.id order_id,a.order_id order_no,u.real_name serviceName,
                a.service_status,
                a.appointment_date,a.user_name,
                a.user_phone,a.address,
            t.name time_name,t.desc,a.status,s.use_time,s.start_time,s.end_time,a.time_id')
                ->find();

            if (!empty($appointment)) {
                $this->appointment_value($appointment);
            } else {
                $appointment = '';
            }

            $skus[$k]['appointment'] = $appointment;
        }

        return $skus;
    }

    /*
     * 预售商品
     */
    function goodsYsDetail($order_id)
    {
        $where = [
            'o.wxapp_id' => self::$wxapp_id,
            'o.is_delete' => 0,
        ];

        //商品列表
        $detail = Db("order_goods")->alias('o_g')
            ->join("order o", 'o_g.order_id = o.order_id', 'left')
            ->where('o.order_id', $order_id)
            ->where('o.pay_status', 20)
            ->whereIn('o.order_status', "10,40")
            ->where('o_g.goods_type', 4)
            ->where($where)
            ->order('o_g.goods_sku_id desc')
            ->field("o_g.goods_sku_id,o_g.goods_id,o_g.order_id,o_g.goods_name,o_g.selling_point,o_g.total_num,
            o_g.type_id,o_g.goods_price")
            ->find();
        if (empty($detail)) {
            $this->error = "订单不存在";
            return false;
        }

        $detail = collection($detail)->toArray();
        $uploadFile = new UploadFileModel;
//        foreach ($detail as $key => $v) {
            $image_id = Db::name('goods_image')->where(['goods_id' => $detail['goods_id'], 'wxapp_id' => self::$wxapp_id])->find();
            $image = $uploadFile->detail($image_id['image_id']);
            $detail['image'] = $image['file_path'];
//        }






//        foreach ($detail as $k => $v) {
            $appointment = $this->alias('a')
                ->join('server_user u', 'u.user_id = a.service_id', 'left')
                ->join('appointment_time t', 't.time_id = a.time_id', 'left')
                ->join('appointment_service s', 's.order_id = a.id', 'left')
                ->where([
                    'user_order_id' => $detail['order_id'],
                    'user_goods_id' => $detail['goods_id'],
                    'user_goods_sku' => $detail['goods_sku_id'],
                ])
                ->where('t.status', 'in', [1, 2])
                ->field('a.id order_id,a.order_id order_no,u.real_name serviceName,a.service_status,
                a.appointment_date,a.user_name,a.user_phone,a.address,
            t.name time_name,t.desc,a.status,s.use_time,s.start_time,s.end_time,a.time_id')
                ->order("a.status desc,a.create_time desc")
                ->select();

            $appointment = collection($appointment)->toArray();
            foreach ($appointment as $kk => $vv) {
                $this->appointment_value($appointment[$kk]);
            }

            $detail['is_yuyue'] = count($appointment) > 0 ? 0 : 1;
            $detail['yuyue'] = $appointment;

//        }

        return $detail;
    }

    /*
     * 线下订单详情
     */
    public function offlineDetail($order_id)
    {
        $where = [
            'wxapp_id' => self::$wxapp_id,
            'is_delete' => 0,
        ];
        $detail = Db("appointment_order")->where($where)->where('id',$order_id)->find();

            $appointment = $this->alias('a')
                ->join('server_user u', 'u.user_id = a.service_id', 'left')
                ->join('appointment_time t', 't.time_id = a.time_id', 'left')
                ->join('appointment_service s', 's.order_id = a.id', 'left')
                ->where([
                    's.order_id' => $detail['id']
                ])
                ->where('t.status', 'in', [1, 2])
                ->field('a.id order_id,a.order_id order_no,u.real_name serviceName,a.service_status,
                a.appointment_date,a.user_name,a.user_phone,a.address,
            t.name time_name,t.desc,a.status,s.use_time,s.start_time,s.end_time,a.time_id')
                ->order("a.status desc,a.create_time desc")
                ->select();

            $appointment = collection($appointment)->toArray();
            foreach ($appointment as $kk => $vv) {
                $this->appointment_value($appointment[$kk]);
            }


        return $appointment;

    }

    /**
     * 商品详情
     * @param $order
     * @return array|bool|false|\PDOStatement|string|\think\Model
     */
    function goodsDetail($order_id)
    {
        $where = [
            'o.wxapp_id' => self::$wxapp_id,
            'o.is_delete' => 0,
        ];

        //商品列表
        $detail = Db("order_goods")->alias('o_g')
            ->join("order o", 'o_g.order_id = o.order_id', 'left')
            ->where('o.order_id', $order_id)
            ->where('o.pay_status', 20)
            ->whereIn('o.order_status', "10,40")
            ->where('o_g.goods_type', 0)
            ->where($where)
            ->order('o_g.goods_sku_id desc')
            ->field("o_g.goods_sku_id,o_g.goods_id,o_g.order_id,o_g.goods_name,o_g.selling_point,o_g.total_num,
            o_g.type_id,o_g.goods_price")
            ->select();
        if (empty($detail)) {
            $this->error = "订单不存在";
            return false;
        }

        $detail = collection($detail)->toArray();
        $uploadFile = new UploadFileModel;
        foreach ($detail as $key => $v) {
            $image_id = Db::name('goods_image')->where(['goods_id' => $v['goods_id'], 'wxapp_id' => self::$wxapp_id])->find();
            $image = $uploadFile->detail($image_id['image_id']);
            $detail[$key]['image'] = $image['file_path'];
        }
        foreach ($detail as $k => $v) {
            $appointment = $this->alias('a')
                ->join('server_user u', 'u.user_id = a.service_id', 'left')
                ->join('appointment_time t', 't.time_id = a.time_id', 'left')
                ->join('appointment_service s', 's.order_id = a.id', 'left')
                ->where([
                    'user_order_id' => $v['order_id'],
                    'user_goods_id' => $v['goods_id'],
                    'user_goods_sku' => $v['goods_sku_id'],
                ])
                ->where('t.status', 'in', [1, 2])
                ->field('a.id order_id,a.order_id order_no,u.real_name serviceName,a.service_status,
                a.appointment_date,a.user_name,a.user_phone,a.address,
            t.name time_name,t.desc,a.status,s.use_time,s.start_time,s.end_time,a.time_id')
                ->order("a.status desc,a.create_time desc")
                ->select();

            $appointment = collection($appointment)->toArray();
            foreach ($appointment as $kk => &$vv) {

                $this->appointment_value($appointment[$kk]);

            }

            $detail[$k]['is_yuyue'] = count($appointment) > 0 ? 0 : 1;
            $detail[$k]['yuyue'] = $appointment;

        }
        return $detail;
    }

    /**
     * 平团商品详情
     * @param $order
     * @return array|bool|false|\PDOStatement|string|\think\Model
     */
    function sharingDetail($order_id)
    {
        $where = [
            'o.wxapp_id' => self::$wxapp_id,
            'o.is_delete' => 0,
        ];

        //商品列表
        $detail = Db("sharing_order_goods")->alias('o_g')
            ->join("sharing_order o", 'o_g.order_id = o.order_id', 'left')
            ->where('o.order_id', $order_id)
            ->where('o.pay_status', 20)
            ->whereIn('o.order_status', "10,40")
            ->where('o_g.goods_type', 0)
            ->where($where)
            ->order('o_g.goods_sku_id desc')
            ->field("o_g.goods_sku_id,o_g.goods_id,o_g.order_id,o_g.goods_name,o_g.selling_point,o_g.total_num,
            o_g.type_id,o_g.goods_price")
            ->select();
        if (empty($detail)) {
            $this->error = "订单不存在";
            return false;
        }

        $detail = collection($detail)->toArray();
        $uploadFile = new UploadFileModel;
        foreach ($detail as $key => $v) {
            $image_id = Db::name('sharing_goods_image')
                ->where(['goods_id' => $v['goods_id'], 'wxapp_id' => self::$wxapp_id])
                ->find();
            $image = $uploadFile->detail($image_id['image_id']);
            $detail[$key]['image_id'] = $image_id['image_id'];
            $detail[$key]['image'] = $image['file_path'];
        }
        foreach ($detail as $k => $v) {
            $appointment = $this->alias('a')
                ->join('server_user u', 'u.user_id = a.service_id', 'left')
                ->join('appointment_time t', 't.time_id = a.time_id', 'left')
                ->join('appointment_service s', 's.order_id = a.id', 'left')
                ->where([
                    'user_order_id' => $v['order_id'],
                    'user_goods_id' => $v['goods_id'],
                    'user_goods_sku' => $v['goods_sku_id'],
                ])
                ->where('t.status', 'in', [1, 2])
                ->field('a.id order_id,a.order_id order_no,u.real_name serviceName,a.service_status,
                a.appointment_date,a.user_name,a.user_phone,a.address,
            t.name time_name,t.desc,a.status,s.use_time,s.start_time,s.end_time')
                ->order("a.status desc,a.create_time desc")
                ->select();

            $appointment = collection($appointment)->toArray();
            foreach ($appointment as $kk => $vv) {
                $this->appointment_value($appointment[$kk]);
            }

            $detail[$k]['is_yuyue'] = count($appointment) == $v['total_num'] ? 0 : 1;
            $detail[$k]['yuyue'] = $appointment;

        }
        return $detail;
    }

    protected function appointment_value(&$appointment)
    {
        $appointment['status_name'] = $this->getServerStatus($appointment['status'], $appointment['service_status']);
        $appointment['serviceName'] = !isset($appointment['serviceName']) || empty($appointment['serviceName']) ? "正在安排师傅" : $appointment['serviceName'];
        $appointment['date_time'] = date("Y-m-d", $appointment['appointment_date']) . ' ' . $appointment['desc'];

        $time_arr = explode(',',$appointment['time_id']);

        $appointment['time_name_arr'] = Db::name('appointment_time')->where(['time_id'=>['in',$time_arr]])->column('name');

        if ($appointment['status'] == 2) {
            $use_time = $appointment['use_time'];
            if ($use_time < 0.01) {
                $timediff = intval($appointment['end_time']) - intval($appointment['start_time']);
                $use_time = number_format($timediff / 60, 0, '.', '');
            }
            $appointment['use_time'] = $use_time . '分钟';
            $appointment['date_time'] = date("Y-m-d", $appointment['appointment_date']) . ' ' . date("H:i", $appointment['start_time']) . "~" . date("H:i", $appointment['end_time']);
        } else {
            $appointment['use_time'] = '等待服务';
        }
    }

    public function getCountServiceList($dataType, $param = [], $limit = 15 )
    {
        $this->getDataType($dataType);

        isset($param['user_id']) && $this->where('o.service_id', $param['user_id']);

//        $is_service = Db("user_address")->where('user_id', $param['user_id'])->value('is_service');
        $is_service = Db("server_user")->where('user_id', $param['user_id'])->find();
        if (!$is_service || $is_service['is_delete'] > 0) {
            $this->error = '当前账号不是服务人员';
            return false;
        }
        $res = [];
        $res['all'] = $this->alias('o')->join('order od', 'o.user_order_id = od.order_id', 'left')->where('o.service_id', $param['user_id'])->where('od.order_status','<>',20)->where('o.is_delete', 0)->count();
        $this->getDataType($dataType);
        $res['today'] = $this->alias('o')->join('order od', 'o.user_order_id = od.order_id', 'left')->where('o.service_id', $param['user_id'])->where('o.appointment_date',strtotime(date('Y-m-d',time())))->where('od.order_status','<>',20)->where('o.is_delete', 0)->count();
        $this->getDataType($dataType);
        $res['tomorrow'] = $this->alias('o')->join('order od', 'o.user_order_id = od.order_id', 'left')->where('o.service_id', $param['user_id'])->where('o.appointment_date',strtotime(date('Y-m-d',strtotime('+1 day'))))->where('od.order_status','<>',20)->where('o.is_delete', 0)->count();
        $this->getDataType($dataType);
        $res['two_day'] = $this->alias('o')->join('order od', 'o.user_order_id = od.order_id', 'left')->where('o.service_id', $param['user_id'])->where('o.appointment_date','>=',strtotime(date('Y-m-d',strtotime('+2 day'))))->where('od.order_status','<>',20)->where('o.is_delete', 0)->count();
        return $res;
    }

    public function getServiceList($dataType, $param = [],$timeType, $limit = 15 )
    {
        $this->getDataType($dataType);
        $this->getTimeType($timeType);

        isset($param['user_id']) && $this->where('o.service_id', $param['user_id']);

//        $is_service = Db("user_address")->where('user_id', $param['user_id'])->value('is_service');
        $is_service = Db("server_user")->where('user_id', $param['user_id'])->find();
        if (!$is_service || $is_service['is_delete'] > 0) {
            $this->error = '当前账号不是服务人员';
            return false;
        }


        $res = $this->alias('o')
//            ->join('appointment_time time', 'o.time_id = time.time_id', 'left')
            ->join('appointment_type type', 'o.type_id = type.type_id', 'left')
            ->join('appointment_service service', 'o.id = service.order_id', 'left')
            ->field("o.order_desc,o.user_id,o.user_order_id,o.user_name,o.user_phone,o.service_name,o.service_name,service.use_time,o.order_id,o.id,o.time_id time_id,
            type.name type_name,offline_name,offline_remark,appointment_date,o.service_status,o.service_time,o.type_id,service.price,o.address,o.status,o.is_offline,o.offline_pay_status,service.server_num,o.offline_from,o.is_img")
            ->order('o.create_time desc')
            ->where('o.is_delete', 0)
            ->paginate($limit, false, [
                'query' => \request()->request()
            ])->each(function ($item, $key) {
                $item['appointment_date'] = date("Y-m-d", $item['appointment_date']);
                $item['service_type_name'] = $this->getServerStatus($item['status'], $item['service_status']);
                if($item['use_time'] <= 0){
                    $item['use_time'] = '未定';
                }
                $time_id = explode(',',$item['time_id']);
                $time_list = Db::name('appointment_time')->where(['time_id'=>['in',$time_id]])->column('desc');
                $str = '';
                foreach ($time_list as $k => $val){
                    if($k == 0){
                        $str .= $val;
                    }else{
                        $str .= '|'.$val;
                    }
                }
                $item['time_name'] = $str;
            });
        $time = time();

        foreach($res as $k=>$v){
            if($v['type_id'] == 7 && $v['service_time']>0){
                if($v['use_time'] > 0){
                    $endtime = $v['use_time']*3600 + $v['service_time'];
                    if($endtime > $time){
                        $hastime = $this->timediff($time,$endtime);
                        $res[$k]['hastime'] = $hastime['hour']."时".$hastime['min']."分";
                    }else{
                        $res[$k]['hastime'] = 0;
                    }
                }

            }else{
                $res[$k]['hastime'] = -1;
            }
            if($v['user_order_id']>0){
                $iscancel = Db::name('order')->where(array('order_id'=>$v['user_order_id']))->find();
                if($iscancel['order_status'] == 20){
                    unset($res[$k]);
                }
            }

        }
        return $res;
    }

    function timediff($begin_time,$end_time)
    {
        if ( $begin_time < $end_time ) {
            $starttime = $begin_time;
            $endtime = $end_time;
        } else {
            $starttime = $end_time;
            $endtime = $begin_time;
        }
        $timediff = $endtime - $starttime;
        $days = intval( $timediff / 86400 );
        $remain = $timediff % 86400;
        $hours = intval( $remain / 3600 );
        $remain = $remain % 3600;
        $mins = intval( $remain / 60 );
        $secs = $remain % 60;
        $res = array("day" => $days, "hour" => $hours, "min" => $mins, "sec" => $secs );
        return $res;
    }

    protected function getDataType($dataType)
    {
        switch ($dataType) {
            case 'all':

                break;
            case 'process':
                $where = " o.service_status=1 or o.service_status=2 or (o.service_status=3 or (o.service_status = 4 and o.status = 1))";
                $this->where('o.is_delete',0)->where($where)->where('o.status','NEQ',3);
                break;
            case 'door':
                $this->where('o.service_status', 2)->where('o.status','NEQ',3);
                break;
            case 'in_progress':
                $where = 'o.service_status = 3 or (o.service_status = 4 and o.status = 1)';
                $this->where($where)->where('o.status','NEQ',3);
                break;
            case "finish":
                $where = 'o.service_status = 4 or (o.status = 2 or o.status = 3)';
//                $this->where('o.service_status', 4)->whereOr('o.status', 'IN',[2,3]);
                $this->where($where);
                break;
        }
    }

    protected function getTimeType($timeType)
    {
        switch ($timeType) {
            case 'all':
                break;
            case 'today':
                $this->where('o.appointment_date',strtotime(date('Y-m-d',time())));
                break;
            case 'tomorrow':
                $this->where('o.appointment_date',strtotime(date('Y-m-d',strtotime('+1 day'))));
                break;
            case 'two_days_later':
                $this->where('o.appointment_date','>=',strtotime(date('Y-m-d',strtotime('+2 day'))));
                break;
        }
    }
    /**
     * 记录预约图片
     * @param $commentList
     * @param $formData
     * @return bool
     * @throws \Exception
     */
    public function saveAllImages($order_id, $image_ids)
    {
        // 生成预约凭证图片数据
        $imageData = [];
        foreach (explode(',', $image_ids) as $imageId) {
            $imageData[] = [
                'order_id' => $order_id,
                'image_id' => $imageId,
                'wxapp_id' => self::$wxapp_id
            ];
        }

        $model = new AppointmentImage;
        return !empty($imageData) && $model->saveAll($imageData);
    }

    public function getDetail($order_id)
    {
        if (!$order_id) {
            $this->error = "订单号为空";
            return false;
        }

        $order = $this->alias("o")
            ->join('appointment_type type', 'type.type_id = o.type_id', 'left')
            ->join('appointment_time time', 'time.time_id = o.time_id', 'left')
            ->where('o.id', $order_id)
            ->field('o.user_name,o.order_id,o.user_phone,o.address,o.appointment_date,
            time.name time_name,time.desc,type.name type_name,o.service_name,o.is_offline,o.status,o.service_status,o.offline_pay_status')
            ->find();
        if (!$order) {
            $this->error = '订单未找到';
            return false;
        }

        $date = $order['appointment_date'];
        $order['appointment_date'] = date("Y-m-d", $date);
        return $order;
    }

    static function detail($id)
    {
        return self::find(['id' => $id]);
    }

    /**
     * 更新确认上门时间
     * @param $order_id
     * @param $time
     * @return $this|bool
     */
    function updateConfirmTime($order_id, $date, $time_id, $user_id)
    {
        if (empty($order_id)) {
            $this->error = '订单号不能为空！';
            return false;
        }

        $order = $this->where('id', $order_id)->find();
        if (empty($order)) {
            $this->error = '订单不存在！';
            return false;
        }

        $date = strtotime($date);
        if ($order['time_id'] == $time_id &&
            $order['appointment_date'] == $date &&
            $order['service_id'] == $user_id
        ) {
            $this->error = '时间已确认';
            return true;
        }

        $exist = $this->where('service_id', $order['service_id'])
            ->where('time_id', $time_id)
            ->where('appointment_date', $date)
            ->find();
        if ($exist) {
            $this->error = "服务人员不可用";
            return false;
        }

        $state = $this->where('id', $order_id)
            ->update([
                'appointment_date' => $date,
                'time_id' => $time_id,
            ]);
        if (!$state) {
            $this->error = "更新失败";
        }

        return $state;
    }

    public function updateServerState($order_id, $state)
    {
        $model = $this->where('id', $order_id)->find();
        $d_time = date('Y-m-d', $model['appointment_date']);
        $t_time = Db::name('appointment_time')->where(['time_id' => $model['time_id']])->value('desc');
        $openid = Db::name('user')->where(['user_id' => $model['user_id']])->value('open_id');
        $type_name = Db::name('appointment_type')->where(['type_id' => $model['type_id']])->value('name');
        $server_user_name = Db::name('server_user')->where(['user_id' => $model['service_id']])->value('real_name');
        if ($state == 2) {
//            $param = [
//                'openid' => $openid,
//                'name' => $model['service_name'],
//                'mobile' => Db::name('server_user')->where(['user_id' => $model['service_id']])->value('mobile'),
//                'time' => $d_time . '' . $t_time
//            ];
            AppointmentRecord::addRecord($order_id,$server_user_name,4);
           //WxMessage::sendMessage(3, $param);
        }
        if ($state == 3) {
            $param = [
                'openid' => $openid,
                'name' => $type_name
            ];
            WxMessage::sendMessage(5, $param);
            AppointmentRecord::addRecord($order_id,$server_user_name,5);
        }
        if ($state == 4) {
            $param = [
                'openid' => $openid,
                'name' => $type_name
            ];
            WxMessage::sendMessage(6, $param);
            AppointmentRecord::addRecord($order_id,$server_user_name,6);
        }

        return $this->where('id', $order_id)
            ->update([
                'service_status' => $state,
                'service_time' => time(),
            ]);
    }

    protected function getServerStatus($status, $server_status)
    {
        $server_status_name = [1 => '待处理', 2 => '待上门', 3 => '进行中', 4 => '待确认', 5 => '已完成', 6 => '已取消'];
        $result = 1;
        switch ($status) {
            case 1:
                switch ($server_status) {
                    case 1:
                        $result = 1;
                        break;
                    case 2:
                        $result = 2;
                        break;
                    case 3:
                        $result = 3;
                        break;
                    case 4:
                        $result = 4;
                        break;
                }
                break;
            case 2:
                switch ($server_status) {
                    case 4:
                        $result = 5;
                        break;
                }
                break;
            case 3:
                $result = 6;
                break;
        }
        return $server_status_name[$result];
    }


    public function addOffline($data = [])
    {

        if (!isset($data['id'])) {
            $this->error = '订单号不能为空';
            return false;
        }

        $model = $this->where('id', $data['id'])->find();

        unset($data['id']);
        if(!$model){
            $this->error = '当前订单不存在，请重新选择';
            return false;
        }

        $data['user_name']   = $model['user_name'];
        $data['user_phone']  = $model['user_phone'];
        $data['address']  = $model['address'];
        $data['service_id']  = $model['service_id'];
        $data['is_self'] = 1;

        if (empty($data['type_id'])) {
            $this->error = '预约类型未选择';
            return false;
        }

        if (empty($data['appointment_date'])) {
            $this->error = '预约日期未选择';
            return false;
        }

        $data['appointment_date'] = strtotime($data['appointment_date']);

        if (empty($data['time_id'])) {
            $this->error = '时间点未选择';
            return false;
        }

        if (empty($data['service_id'])) {
            $this->error = '服务人员未选择';
            return false;
        }

        if (empty($data['offline_name'])) {
            $this->error = '请输入服务内容';
            return false;
        }

        if (empty($data['money'])) {
            $data['money'] = 0;
        }

        $serverName = Db("server_user")->where("user_id", $data['service_id'])
            ->where('wxapp_id', self::$wxapp_id)->value('real_name');
        if (empty($serverName)) {
            $this->error = '服务人员信息未找到';
            return false;
        }

        $data['service_name'] = $serverName;
        $data['is_offline'] = 1;

        $order = [
            'order_no' => OrderService::createOrderNo(),
            'total_price' => $data['money'],
            'order_price' => $data['money'],
        ];
        Db::startTrans();

        $use_time = $data['use_time'];
        $order_id = Db("order")->insertGetId($order);
        $data['user_order_id'] = $order_id;
        $data['wxapp_id'] = self::$wxapp_id;
        $status = $this->allowField(true)->save($data);

        $ServiceModel = new ServiceModel();
        $ServiceModel->add_service($this->id, $data['service_id'], $data['money'], $use_time);

        if ($status && $order_id > 0) {
            Db::commit();
            return true;
        } else {
            Db::rollback();
            return false;
        }
    }
}
